package com.example.a2032.fragment;

import android.content.Context;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.a2032.R;
import com.example.a2032.Utils.BleSdk;
import com.example.a2032.Utils.DateUtils;
import com.example.a2032.Utils.SerialPortUtil;
import com.example.a2032.Utils.Utils;
import com.example.a2032.adapter.SleepHistoryAdapter;
import com.example.a2032.entity.SleepData;
import com.example.a2032.viewmodel.SleepDataViewModel;

import java.util.Date;
import java.util.List;

import butterknife.BindArray;
import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link SleepHistoryFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class SleepHistoryFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.RecyclerView_Sleep)
    RecyclerView RecyclerViewSleep;
    @BindArray(R.array.sleepHistory_array)
    String[]sleepArray;
    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private SleepDataViewModel sleepDataViewModel;
    private SleepHistoryAdapter sleepHistoryAdapter;

    public SleepHistoryFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @return A new instance of fragment HistoryFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static SleepHistoryFragment newInstance() {
        SleepHistoryFragment fragment = new SleepHistoryFragment();
        Bundle args = new Bundle();
//        args.putString(ARG_PARAM1, param1);
//        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_history, container, false);
        ButterKnife.bind(this, view);
        init();
        return view;

    }

    private void init() {
        if (sleepDataViewModel == null) {
            Log.i(TAG, "init: ");
            sleepDataViewModel = new ViewModelProvider(this).get(SleepDataViewModel.class);
        }
        int[]sleepData=new int[3];
         sleepHistoryAdapter = new SleepHistoryAdapter(sleepArray, sleepData);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        RecyclerViewSleep.setLayoutManager(linearLayoutManager);
        RecyclerViewSleep.setAdapter(sleepHistoryAdapter);

       ;
    }

    private void getSleepData(){
        String today=DateUtils.getDefaultToday(new Date());
        String startDate= DateUtils.getYesterdayDateString(today);

        Log.i(TAG, "getSleepData: "+startDate+" "+today);
        sleepDataViewModel.getSleepData(startDate+" 12:00:00",today+" 12:00:00").observe(getViewLifecycleOwner(), new Observer<List<SleepData>>() {
            @Override
            public void onChanged(List<SleepData> sleepData) {
                int[]sleepLevels=new int[4];
                int sleepCount=0;
                for(SleepData sleepData4:sleepData){
                    String sleepQ=sleepData4.getSleepQuality();
                    String[]array=sleepQ.split(" ");
                    for(String sleepValueString:array){
                        int sleepValue=Integer.valueOf(sleepValueString);
                        sleepLevels[Utils.getSleepLevel(sleepValue/5)]++;
                        sleepCount++;
                    }
                }
                int lightSleep=sleepLevels[1]*5;
                int deepSleep=sleepLevels[0]*5;
                int total=sleepCount*5;
                int[]sleepDatas=new int[]{lightSleep,deepSleep,total};
                sleepHistoryAdapter.updateData(sleepDatas);
            }
        });
    }
    private static final String TAG = "SleepHistoryFragment";
    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        Log.i(TAG, "onAttach: ");
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        Log.i(TAG, "onHiddenChanged: "+hidden);
    }

    @Override
    public void onResume() {
        super.onResume();
        getSleepData();
        SerialPortUtil.getInstance().sendData(BleSdk.getAllSleepData());
        SerialPortUtil.getInstance().sendData(BleSdk.getSleepData());
    }
}